package com.tan.androidtest.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Locale;

/**
 * 服务中 使用AlarmManager实现心跳
 */

public class TestService extends Service {


    private int count = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("==--", "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("==--", "onStartCommand");
        reStartIntent();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 开始心跳检测
     */
    private void reStartIntent() {
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        //int anHour = 60 * 60 * 1000; // 这是一小时的毫秒数
        long triggerAtTime = SystemClock.elapsedRealtime() + 6000;
        Intent i = new Intent(this, AlarmReceiver.class);
        i.setAction("com.android.test");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
    }

    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, TestService.class);
            context.startService(i);
        }
    }

    /**
     * 写时间到本地文件
     */
    private void writeFile() {
        String filePath;
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) {
            filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "test.txt";
        } else
            filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + "test.txt";

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file);
            java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("HH:mm:ss", Locale.CHINA);
            Date date = new Date();
            outStream.write(format.format(date).getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("==--", "onDestroy ");
    }
}
